<template>
	<Modal v-model="flag" :mask-closable="false" :width="800" title="选择人员" footer-hide>
		<Row type="flex">
			<Col span="12">
				<div class="org-list-main">
					<Input search placeholder="搜索员工" v-model="keyword" @input="searchEmp" />
					<!-- 搜索员工列表 -->
					<div v-if="keyword" class="search-list-panel">
						<Spin size="large" fix v-if="loading"></Spin>
						<!-- 用户 -->
						<CheckboxGroup v-model="checkedIds">
							<Checkbox class="list-cell" v-for="user in searchList" :key="user.empNo" :label="user.empNo" @click.native="(e) => handleChecked(e, user, 'emp')">
								<div class="user-info">
									<span class="list-cell-text">{{ user.empName }}（{{ user.empNo }}）</span>
								</div>
							</Checkbox>
						</CheckboxGroup>
					</div>
					<!-- 组织机构列表 -->
					<div class="org-list-panel" v-else>
						<div class="org-list-panel-hd">
							<!-- 面包屑导航 -->
							<Breadcrumb separator=">" class="org-list-crumb">
								<BreadcrumbItem class="org-list-crumb__item" v-for="(crumb, index) in crumbs" :key="index" @click.native="popStack(crumb)">{{ crumb.Name }}</BreadcrumbItem>
							</Breadcrumb>
						</div>
						<div class="org-list-panel-bd">
							<Spin size="large" fix v-if="loading"></Spin>
							<div class="check-all" v-show="showCheckAll">
								<Checkbox @on-change="checkAll" v-model="allcheck">全选</Checkbox>
							</div>
							<!-- 公司 -->
							<CheckboxGroup v-model="checkedDepIds" @on-change="isAllCheck">
								<div v-for="dept in current.Children" :key="dept.orgNo" class="list-cell">
									<Checkbox :key="dept.orgNo" :label="dept.orgNo" class="list-cell-left" @click.native="(e) => handleChecked(e, dept, 'dept')">
										<div class="dept-info">
											<img :src="orgIcon" width="20" />
											<span class="list-cell-text">{{ dept.orgName }} </span>
										</div>
									</Checkbox>
									<div class="list-cell-right">
										<Button @click="getNextData(dept)" type="text" :disabled="checkedDepIds.indexOf(dept.orgNo) > -1">下级</Button>
									</div>
								</div>
							</CheckboxGroup>
							<!-- 用户 -->
							<CheckboxGroup v-model="checkedIds" @on-change="isAllCheck">
								<Checkbox class="list-cell" v-for="user in current.Users" :key="user.empNo" :label="user.empNo" @click.native="(e) => handleChecked(e, user, 'emp')">
									<div class="user-info">
										<span class="list-cell-text">{{ user.empName }}（{{ user.empNo }}）</span>
									</div>
								</Checkbox>
							</CheckboxGroup>
						</div>
					</div>
				</div>
			</Col>
			<div class="split"></div>
			<Col span="12">
				<div style="padding-left: 16px">
					<span>已选择（{{ selectUserNum }}）</span>
				</div>
				<div class="selected-user">
					<Tag class="selected-user__item" v-for="(tag, index) in checkedtags" :key="index" closable @on-close="handleClose(tag.No, tag.Type, index)">{{ tag.Name }}</Tag>
				</div>
			</Col>
		</Row>
		<div class="footer">
			<Button type="default" @click="hanldCancel">取消</Button>
			<Button type="primary" @click="hanldSubmit">确定</Button>
		</div>
	</Modal>
</template>
<script>
import { AIMaasHttp } from '@/api/aimaas.js'
import { EmpSelector } from '@/api/user.js'
import orgIcon from '@/assets/images/org.svg'
export default {
	name: 'EmpSelector',
	props: {
		randIndex: {
			type: Number,
			default: () => {
				return 0
			}
		}
	},
	data() {
		return {
			flag: false,
			loading: false,
			crumbStack: [],
			current: {},
			checkedIds: [],
			checkedDepIds: [],
			checkedtags: [],
			users: [],
			depts: [],
			orgIcon,
			allcheck: false,
			showCheckAll: true,
			keyword: '',
			searchList: []
		}
	},
	computed: {
		crumbs() {
			return this.crumbStack.map((val) => {
				return {
					ID: val.orgNo,
					Name: val.orgName
				}
			})
		},
		selectUserNum() {
			// let depNum = this.checkedtags.reduce((userNum, currentTag) => {
			// 	return userNum + currentTag.UserNum
			// }, 0)
			// return depNum
			return this.checkedtags.length
		}
	},
	methods: {
		hanldCancel() {
			this.flagSet(false)
		},
		flagSet(boolflag) {
			this.flag = boolflag
		},
		hanldSubmit() {
			this.flagSet(false)
			this.$emit('on-success-callback', this.checkedtags)
		},
		getNextData(data) {
			this.current = data
			if (this.current.Users == undefined) {
				this.getOrgUserList(this.current.orgNo, this.current.orgName)
			} else {
				this.crumbStack.push(this.current)
			}
		},
		async getRootOrg() {
			const res = await AIMaasHttp.MasterData.GetOrgEmpList({ orgNo: '' })
			const { code, data } = res.data
			if (code == '0') {
				this.current = Object.assign({}, data.orgList[0])
				this.getOrgUserList(this.current.orgNo)
			}
		},
		getOrgUserList(orgNo) {
			this.loading = true
			AIMaasHttp.MasterData.GetOrgEmpList({ orgNo: orgNo })
				.then((res) => {
					this.loading = false
					let data = res.data.data
					this.current.Users = data.empList
					this.current.Children = data.orgList
					if (data.empList.length == 0 && data.orgList.length == 0) {
						this.showCheckAll = false
					} else {
						this.showCheckAll = true
					}
					this.users.push(...this.current.Users)
					this.depts.push(...this.current.Children)
					this.crumbStack.push(this.current)
				})
				.catch((err) => {
					this.loading = false
					console.log(err)
				})
		},
		popStack(crumb = {}) {
			console.log('pop', crumb)
			// 出栈时 移除 crumb 及上层所有crumb。
			let stack = this.crumbStack
			let index = stack.findIndex((item) => item.orgNo === crumb.ID)
			let current = stack[index]
			if (index !== stack.length - 1) {
				stack.splice(index + 1)
				this.current = current
			}
			this.isAllCheck()
		},
		handleClose(id, type, index) {
			this.checkedtags.splice(index, 1)
			if (type == 'emp') {
				let index = this.checkedIds.findIndex((cid) => cid === id)
				if (index != -1) {
					this.checkedIds.splice(index, 1)
				}
			} else {
				let index = this.checkedDepIds.findIndex((cid) => cid === id)
				if (index != -1) {
					this.checkedDepIds.splice(index, 1)
				}
			}
			this.isAllCheck()
		},
		handleChecked(e, obj, type) {
			if (e.target.checked != undefined) {
				let checked = e.target.checked
				if (checked) {
					this.checkedtags.push({
						No: type == 'dept' ? obj.orgNo : obj.empNo,
						Name: type == 'dept' ? obj.orgName : obj.empName,
						Type: type,
						UserNum: type == 'dept' ? obj.TotalStaff : 1
					})
				} else {
					let no = type == 'dept' ? obj.orgNo : obj.empNo
					let index = this.checkedtags.findIndex((item) => item.No === no && item.Type === type)
					if (index !== -1) {
						this.checkedtags.splice(index, 1)
					}
				}
			}
		},
		checkAll(checked) {
			let allDep = this.current.Children.map((a) => a.orgNo)
			let alluser = this.current.Users.map((a) => a.empNo)
			let tagDept = this.current.Children.map((item) => ({ No: item.orgNo, Name: item.orgName, Type: 'dept', UserNum: item.TotalStaff }))
			let tagUser = this.current.Users.map((item) => ({ No: item.empNo, Name: item.empName, Type: 'emp', UserNum: 1 }))
			if (checked) {
				let checkedIds = [...this.checkedIds, ...alluser]
				let checkedDepIds = [...this.checkedDepIds, ...allDep]
				//去重
				this.checkedIds = checkedIds.filter((item, index, arr) => {
					return arr.indexOf(item) == index
				})
				//去重
				this.checkedDepIds = checkedDepIds.filter((item, index, arr) => {
					return arr.indexOf(item) == index
				})
				let alltag = [...this.checkedtags, ...tagDept, ...tagUser]
				//标签去重
				this.checkedtags = alltag.reduce((pre, cur) => {
					if (!pre.find((item) => item.No === cur.No && item.Type === cur.Type)) {
						pre.push(cur)
					}
					return pre
				}, [])
			} else {
				let checkedIds = this.checkedIds.filter((item) => {
					return alluser.indexOf(item) == -1
				})
				this.checkedIds = [...checkedIds]
				let checkedDepIds = this.checkedDepIds.filter((item) => {
					return allDep.indexOf(item) == -1
				})
				this.checkedDepIds = [...checkedDepIds]
				let tags = [...tagDept, ...tagUser]
				let checkedtags = this.checkedtags.filter((item) => {
					return tags.every((a) => a.No != item.No || a.Type != item.Type)
				})
				this.checkedtags = checkedtags
			}
		},
		isAllCheck() {
			let allDep = this.current.Children.map((a) => a.orgNo)
			let alluser = this.current.Users.map((a) => a.empNo)
			let isInclude = [...allDep, ...alluser].every((val) => [...this.checkedIds, ...this.checkedDepIds].includes(val))
			if (isInclude) {
				this.allcheck = true
			} else {
				this.allcheck = false
			}
		},
		init(selUsers, selDepts) {
			this.checkedtags = [...selUsers, ...selDepts]
			this.checkedIds = selUsers.map((item) => item.No)
			this.checkedDepIds = selDepts.map((item) => item.No)
			this.crumbStack = []
			this.users = []
			this.depts = []
			this.allcheck = false
			this.getRootOrg('')
		},
		async searchEmp() {
			let info = {
				Fields: ['EmployeeNo', 'EmployeeName'],
				Conditions: [
					{
						Field: 'EmployeeNo',
						Value: this.keyword,
						Operator: 6,
						Relation: 1,
						Prefix: 0
					},
					{
						Field: 'EmployeeName',
						Value: this.keyword,
						Operator: 6,
						Relation: 1,
						Prefix: 0
					},
					{
						Field: 'DomainName',
						Value: this.keyword,
						Operator: 6,
						Relation: 1,
						Prefix: 0
					}
				],
				SortExpression: 'EmployeeNo desc,EmployeeName asc',
				PageIndex: 1,
				PageSize: 100
			}
			this.loading = true
			const res = await EmpSelector(info)
			this.loading = false
			const { List } = res.data
			this.searchList = List.map((item) => ({ empNo: item.EmployeeNo, empName: item.EmployeeName }))
			console.log(this.searchList)
		}
	}
}
</script>
<style lang="less" scoped>
.split {
	display: block;
	position: absolute;
	top: 51px;
	bottom: 0;
	left: 50%;
	border: 1px dashed #eee;
}
.footer {
	text-align: right;
	.ivu-btn {
		margin-right: 10px;
	}
}
.org-list-main {
	.search-list-panel {
		overflow: auto;
		.list-cell {
			display: flex;
			align-items: center;
			min-height: 46px;
			padding: 8px 16px;
			.list-cell-text {
				margin-left: 10px;
			}
		}
	}
	.org-list-panel {
		display: flex;
		flex-direction: column;
		min-height: 400px;
		max-height: 100%;
		width: 100%;
		.org-list-panel-hd {
			padding: 16px;
		}

		.org-list-panel-bd {
			flex: 1;
			overflow: auto;
			.check-all {
				padding-left: 16px;
				/deep/.ivu-checkbox {
					margin-right: 10px;
				}
			}
			.list-cell {
				display: flex;
				align-items: center;
				min-height: 46px;
				padding: 8px 16px;
				.list-cell-text {
					margin-left: 10px;
				}
				.list-cell-left {
					display: flex;
					flex: 1 1 auto;
					.dept-info {
						display: flex;
						align-items: center;
						margin-left: 10px;
					}
				}
			}
		}
	}
}
.selected-user {
	display: flex;
	flex-wrap: wrap;
	padding: 16px;
	.selected-user__item {
		margin-right: 8px;
		margin-bottom: 8px;
		cursor: pointer;
	}
}
</style>

